/*  
 * cafe-nCharts.js
 * @Author :      PanRS
 * @CreateDate :  2017年8月14日
 * Copyright (c) 2017 NRIET.　
 * TODO
 * 		
 */

;(function(Factory){
	var CafeJS = window.CafeCxtPath;
	var JN = "/static/widgets/cafejs/script/officectrl/cafe-config.json", 
		W = window, J = $ = jQuery,
		BURL = W.CafeCxtPath? W.CafeCxtPath : "/",
		JH = J("<ul class='tools-header'>"), JB = J("<div class='tools-body'>");
	
	var TS = [{'id': 'his_ts', 'nm': '历史产品'},
	          {'id': 'aux_ts', 'nm': '辅助工具'},
	          {'id': 'coll_ts', 'nm': '我的收藏'}];
	
	var opts = null;
	
	function _ajaxJn(setting){
		var tbs = ['his_ts'], defutTb = 0;
		if(setting){
			opts = setting;
			tbs = setting.tabs? setting.tabs: tbs;
			defutTb = setting.index? setting.index: defutTb;
		}
		
		J("div.online-container-tools").empty().append(JH);
		
		J.each(TS, function(i, o){
			var zcls = i == defutTb ? 'actived': '';
			if(J.inArray(o.id, tbs) == 0){
				JH.append(J("<li class='tools-header-tab " + zcls + "' id='" + o.id + "'>").html(o.nm));
				buildHistory();
			}else{
				JH.append(J("<li class='tools-header-tab' id='" + o.id + "'>").html(o.nm));
				if(i == 2){
					loadCollection();
				}else{
					buildFzgj();
				}
			}
		});
	}
	
	// 产品收藏
	function loadCollection(){
		var $coll = $('<div id="coll-content">').hide();
		JB.append($coll);
		
		$.ajax({ 
			url: CafeJS + "jcpt/addColl.do", 
			type: "GET",
			dataType: "html",
			crossDomain: true,
			async: false,
			context: $coll, 
			success: function(rest, textStatus, jqXHR){
				if(jqXHR.status == 200 && textStatus == 'success'){
					$(this).html(rest); 
				}
			},
			error: function (XHR, textStatus, errorThrown) {console.log(errorThrown);},
			complete: function(XHR, TS){}
		});
	}
	
	// 历史产品
	function buildHistory(){
		var $history = $('<div class="histroy-contnet">');
		var $time = $('<div class="head-query-time-content">'+
						'<div class="head-query-time-label">发布时间：</div>'+
						'<div class="timeContent"><div></div><input id="historyDate" class="Wdate" onfocus="WdatePicker({dateFmt:\'yyyy-MM-dd\'})" readonly/></div>'+
						'<div class="head-query-time-line">--</div>'+
						'<div class="timeContent"><div></div><input id="historyDate2" class="Wdate" onfocus="WdatePicker({dateFmt:\'yyyy-MM-dd\'})" readonly/></div>'+
						'<div class="query-btn">'+
							'<div class="query-data-btn"><i class="cafe-ifont cafe-ic-chaxun"></i><span>查询</span></div>'+
							'</div>'+
					'</div>');
		$history.append($time);
		var $timeSel = $('<div class="time-select-content">');
		var $year = $('<div class="year-select">');
		$year.append('<div class="left-arrow"><i class="cafe-ifont cafe-ic-xiangzuo4"></i></div>');
		$year.append('<div class="year-select-area">2017</div>');
		$year.append('<div class="right-arrow"><i class="cafe-ifont cafe-ic-xiangyou"></i></div>');
		var $month = $('<div class="month-select">');
		var $monSel = $('<div class="month-select-area">');
		for(var i = 1; i < 13; i++){
			var $mon = $('<div class="month-btn" item="'+ i +'">'+ i +'</div>');
			$monSel.append($mon);
		}
		

		var season = [ "第一季度", "第二季度", "第三季度", "第四季度" ];
		for(var j = 1; j < season.length + 1; j++){
			var $season = $('<div class="season-btn" item="'+ j +'">'+ season[j - 1] +'</div>');
			$monSel.append($season);
		}
		
		$month.append($monSel);
		
		var $table = $('<div class="nriet-grid">');
		
		$history.append($timeSel.append($year).append($month)).append($table);
		J("div.online-container-tools").append(JB.append($history));
		
		loadTime();
		queryDataTable();
		//loadDataTable();
		bindRightEvent();
	}
	
	//查询数据
	function queryDataTable(){    
		var proid = window.top.document.getElementsByClassName("active")[0].getAttribute("data-for");
		var params = {
			proId : proid,/*"WEEKP_DIAS",*/
			areaCode : user && user.codeId ? user.codeId : "35",
			sTime : sTime+" 00:00:00",
			lTime : lTime+" 23:59:59",
			types : "DOC"
		};
		
		$.ajax({
			type : 'POST',
			url : CafeJS + "historyData/queryDataInfo.do",
			data : params,
			dataType : 'json',
			success : function(data) {
				if (data.success && data.params.info) {
					var info = data.params.info.DOC;
					dataInfo = info;
					loadDataTable(dataInfo);
				}
			}
		});
	}
	
	//加载列表数据 
	function loadDataTable(data){
		var that = this;
		var $contain = $(".nriet-grid").empty();
	
		var headInfo = [{key : "TITLE0", val : "序号"}, {key : "TITLE2", val : "时间"}, {key : "TITLE1", val : "产品名称"}, {key : "TITLE3", val : "操作"}];
		
		var css = {TITLE0 : 50, TITLE2 : 140, TITLE1 : 240, TITLE3 : 100};
		var dataInfo = data.body;
		//标题
		var $headDiv = $("<div class='headDiv'></div>");
		var $headTable = $("<table class='headTable'></table>");
		
		var thead_tr = $("<tr>");
		var nowShowTitleKey = [];
		for(var i = 0; i < headInfo.length; i++){
			var eachInfo = headInfo[i];
			var each_key = eachInfo["key"];
			var each_td = eachInfo["val"];
			if(each_td){
				$td = $("<th>"+each_td+"</th>");
				$td.css({'width' : css[each_key]});
				thead_tr.append($td);
				nowShowTitleKey.push(each_key);
			}
		}
		$headTable.append(thead_tr);
		
		$headDiv.append($headTable);
		//数据
		var $dataDiv = $("<div class='dataDiv'></div>");
		var $dataTable = $("<table class='dataTable'></table>");
		
		for(var i = 0; i < dataInfo.length; i++){
			var eachInfo = dataInfo[i];
			var each_tr = $("<tr>");
			each_tr.data("info", eachInfo);
			if(Number(i) % 2 == 0){
				each_tr.addClass("double");
			}
			
			for(var j = 0; j < nowShowTitleKey.length; j++){
				var each_key = nowShowTitleKey[j];
				var each_td = eachInfo[each_key];
				if(each_key == "TITLE0"){
					each_td = Number(i) + 1; 
				}
				
				if(each_key == "TITLE1"){
					each_td = eachInfo.TITLE3;
				}
				
				var $td = $("<td title='" + (each_key == "TITLE2" ? each_td : "") + "'>");
				
				if(each_key == "TITLE3"){
					var $look = $('<div class="look-btn">').text("查看");
					var $quote = $('<div class="quote-btn">').text("引用正文");
					$td.append($look).append($quote);
				}else{
					$td.text(each_td);
				}
				
				$td.css({'width' : css[each_key]});
				each_tr.append($td);
			}
			$dataTable.append(each_tr);
		}
		$dataDiv.append($dataTable);
		
		$contain.append($headDiv).append($dataDiv);
		
		bindBtnsEvents($contain);
	}
	
	function bindBtnsEvents(){
		$(".online-container-tools").undelegate(".look-btn", "click").delegate(".look-btn", "click", function(e){
			e.stopPropagation();
			popWord($(this));
		});
	}
	
	function popWord($obj){
		var container = window.top.document.getElementsByClassName("online-container-pop-pages");
		var filePath = $obj.closest("tr").data("info").HTTP_PATH;
		var $iframe = $("<iframe src='"+filePath+"'></iframe>");
		window.open(filePath, "newWindow", 'frame=yes;fullscreen=yes;resizable=yes;height=800;width=600;');
	}
	
	function loadTime(){
		var time = new Date().getTime();
		var date = new Date().getDate() - 1;
		lTime = dateUtil.convertDateForHourToString(new Date(time)).substr(0, 10);
			time = time - date * 24 * 60 * 60 * 1000; 
		sTime = dateUtil.convertDateForHourToString(new Date(time)).substr(0, 10);
		var year = lTime.substring(0,4);
		$("#historyDate").val(sTime);
		$("#historyDate2").val(lTime);
		$(".year-select-area").text(year);
	}
	
	//时间事件
	function bindRightEvent(){
		//年切换 - 向左
		$('div.online-container-tools').undelegate(".left-arrow", "click").delegate(".left-arrow", "click", function(e){
			e.stopPropagation();
			var year = $(this).siblings(".year-select-area").text();
			var newYear = parseInt(year) - 1;
			$(".year-select-area").text(newYear);
			$(".selected").removeClass("selected");
			modifiedTimeArea(newYear);

		});
		
		//年切换 - 向右
		$('div.online-container-tools').undelegate(".right-arrow", "click").delegate(".right-arrow", "click", function(e){
			e.stopPropagation();
			var year = $(this).siblings(".year-select-area").text();
			var newYear = parseInt(year) + 1;
			$(".year-select-area").text(newYear);
			$(".selected").removeClass("selected");
			modifiedTimeArea(newYear);
		});
		
		//年点击
		$('div.online-container-tools').undelegate(".year-select-area", "click").delegate(".year-select-area", "click", function(e){
			e.stopPropagation();
			modifiedTimeArea( $(this).text());
		});
		
		//季度
		$('div.online-container-tools').undelegate("div.season-btn", "click").delegate('div.season-btn', "click",function(e){
			e.stopPropagation();
			if(!$(this).hasClass("selected")){
				var jidu = $(this).attr('item');
				$(".selected").removeClass("selected");
				$(this).addClass("selected");
				modifiedTimeArea("", jidu);
			}
		});
		
		//月份
		$('div.online-container-tools').undelegate("div.month-btn", "click").delegate("div.month-btn", "click",function(e){
			e.stopPropagation();
			if(!$(this).hasClass("selected")){
				$(".selected").removeClass("selected");
				$(this).addClass("selected");
				var month = $(this).attr("item");
				modifiedTimeArea("", "", month.toString());
			}
		});
		
		//查询
		$('div.online-container-tools').undelegate("div.query-data-btn", "click").delegate("div.query-data-btn", "click", function(){
			queryDataTable();
		});
	}
	
	//修改时间  
	function modifiedTimeArea(newYear, jidu, month){
		sTime = $("#historyDate").val();
		lTime = $("#historyDate2").val();
		var sTime_year = sTime.substring(0, 4);
		var lTime_year = lTime.substring(0, 4);
		var sTime_month = sTime.substring(5, 7);
		var lTime_month = lTime.substring(5, 7);
		var sTime_day = sTime.substring(8, 10);
		var lTime_day = lTime.substring(8, 10);
		
		if(jidu){
			var year = parseInt($(".year-select-area").text());
			switch(jidu){
				case '1' :
					sTime = year + "-01-01";
					lTime = year + "-03-31";
					break;
				case '2' :
					sTime = year + "-04-01";
					lTime = year + "-06-30";
					break;
				case '3' :
					sTime = year + "-07-01";
					lTime = year + "-09-30";
					break;
				case '4' :
					sTime = year + "-10-01";
					lTime = year + "-12-31";
					break;
			}
		}else if(month){
			var year = parseInt($(".year-select-area").text());
			sTime = year + "-" + (month.length > 1 ? month : "0" + month) + "-01";
			lTime = year + "-" + (month.length > 1 ? month : "0" + month) + "-" + new Date(new Date(year, month, 1).getTime() - 1).getDate();
		}else{
			sTime = newYear + "-01-01";
			lTime = newYear + "-12-31";
		}
		
		$("#historyDate").val(sTime);
		$("#historyDate2").val(lTime);
		
	}
	
	// 辅助工具
	function buildFzgj(){
		var JCONTENT = J("div.online-container-tools");
		J.getJSON(BURL + JN, function(data){
			if(data){
				buildDom(data);
			}
		});
		function buildDom(data){
			var JBU = J("<ul class='tools-body-content'>").hide();
			J.each(data, function(key, obj){
				if(obj){
					var JE = $("<li class='ele " + key + "'>");
					JE.append(J("<i class='header'>").html(obj.name));
					J.each(obj.members, function(j, e){
						var JMEM = J("<i class='mem' data-code='" + e.code + "'>");
						JMEM.attr({title: e.descr}).html(e.descr);
						JE.append(JMEM);
					});
					JBU.append(JE);
				}
				JB.append(JBU);
			});
		}
		JCONTENT.empty().append(JH).append(JB);
	}

	function _evs(){
		
		var Jmems = J('i.mem');
		Jmems.off('click').on('click', function(e){
			var POCtrl = document.getElementById("PageOfficeCtrl1");
			console.log(POCtrl);
			if(POCtrl){
				var dalist = POCtrl.DataRegionList;
				console.log(dalist);
			}
			console.log(this);
			//替换选中的文本
		    function selectbox(a){
		    	var value = a.innerHTML;
		    	
		    	var mac = "Function myfunc()" + " \r\n"
	            + "Dim r As Range " + " \r\n"
	            + "Set r = Application.Selection.Range " + " \r\n"
	            + "r.Text = \"" + value + "\"" + " \r\n"
	            + "End Function " + " \r\n";
		    	POCtrl.RunMacro("myfunc", mac);
		    }
		    selectbox(this);
		});
		
		// tab切换事件
		$(".tools-header-tab").off("click").on("click", function(){
			$(this).addClass("actived").siblings().removeClass("actived");
			if($(this).is("#his_ts")){
				$(".histroy-contnet").show();
				$(".tools-body-content, #coll-content").hide();
			}else if($(this).is("#aux_ts")){
				$(".histroy-contnet, #coll-content").hide();
				$(".tools-body-content").show();
			}else if($(this).is("#coll_ts")){
				$("#coll-content").show();
				$(".tools-body-content, .histroy-contnet").hide();
			}
		});
	}
	
	if(typeof Factory === 'function'){
		var obj = {
			buildDoms: _ajaxJn,
			events: _evs,
		};
		Factory(obj);
	}
	
})(function(CallObj){
	if(CallObj){
		window.OCtrl = function(setting){
			CallObj.buildDoms(setting);
			window.setTimeout(function() {
				CallObj.events();
			}, 200);
		};
	}
});